package com.sgzn.sgpay.service.support;

import com.sgzn.sgpay.constants.Constants;
import com.sgzn.sgpay.constants.SgsRespCodeConstants;
import com.sgzn.sgpay.enums.SgsResponseCode;
import com.sgzn.sgpay.model.response.ConvertCodeResponse;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Component;

import java.util.Map;

/**
 * 响应码转换
 * @author zhongzhongyong
 * @version Id: ConvertResponseCodeHandler.java, v 0.1 2018/4/3 23:37 zhongzhongyong Exp $$
 */
@Slf4j
@Component
public class ConvertResponseCodeHandler {

    /**
     * 响应码转换
     * @param code
     * @return
     */
    public ConvertCodeResponse convertResponseCode(String code, String msg) {
        ConvertCodeResponse response = new ConvertCodeResponse(code, msg);
        if (StringUtils.isEmpty(code)) {
            return response;
        }
        if (code.length() == 11) {
            convertInternalCode(code, msg, response);
        }
        return response;
    }



    /**
     * 内部11位编码转换
     * @param code
     * @param msg
     * @param response
     */
    private void convertInternalCode(String code, String msg, ConvertCodeResponse response) {
        Map<String, String> parameters = response.getExtraParameters();

        String statusCode = code.substring(5, 7);
        if (SgsRespCodeConstants.SUCCESS_STATUS_CODE.equals(statusCode)) {
            response.setResponseCode(SgsResponseCode.C200);
            //业务成功(最后两位为00)时设置success为true
            response.setSuccess(true);
        } else {
            parameters.put(Constants.REQUEST_ATTR_RESPONSE_FAIL_REASON, String.format("CODE:%s - DESC:%s", code, msg));
            if (SgsRespCodeConstants.SYSTEM_ERROR_STATUS_CODE.equals(statusCode)) {
                response.setResponseCode(SgsResponseCode.C503);
            } else if (SgsRespCodeConstants.WAITTING_HANDLE_STATUS_CODE.equals(statusCode)) {
                parameters.put(Constants.REQUEST_ATTR_RESPONSE_HANDLING_FLAG, "HANDLING");
                response.setResponseCode(SgsResponseCode.C011007);
            } else if (SgsRespCodeConstants.WAITTING_RESPONSE_STATUS_CODE.equals(statusCode)) {
                parameters.put(Constants.REQUEST_ATTR_RESPONSE_HANDLING_FLAG, "HANDLING");
                if (Constants.AUDIT_CODE.equals(code.substring(5, 11))) {
                    //审核中
                    response.setResponseCode(SgsResponseCode.C_WAIT_AUDIT);
                } else {
                    response.setResponseCode(SgsResponseCode.C_WAIT_BANK_RESP);
                }
            } else if (SgsRespCodeConstants.OTHER_EORROR_STATUS_CODE.equals(statusCode)) {
                response.setErrorCode(code.substring(3, 5) + code.substring(7, 11));
            }
        }
    }

}
